package com.zhan.rkforum.controller;


import com.zhan.rkforum.bean.Event;
import com.zhan.rkforum.bean.User;
import com.zhan.rkforum.event.EventProducer;
import com.zhan.rkforum.service.FollowService;
import com.zhan.rkforum.util.CommunityConstant;
import com.zhan.rkforum.util.CommunityUtil;
import com.zhan.rkforum.util.HostHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class FollowController implements CommunityConstant {

    private final Logger logger = LoggerFactory.getLogger(FollowController.class);

    @Autowired
    private FollowService followService;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private HostHolder hostHolder;

    @PostMapping("/follow")
    @ResponseBody
    public String follow(int entityType, int entityId){
        User user = hostHolder.getUser();
        int userId = user.getId();
        try{
            followService.follow(entityType, entityId,userId);
        }catch (Exception e){
            logger.error("followService的follow方法报异常"+ e.getMessage());
            return CommunityUtil.getJsonString(0, "关注失败！", null);
        }

        //触发关注事件
        Event event = new Event();
        event.setUserId(userId)
                .setTopic(TOPIC_FOLLOW)
                .setEntityId(entityId)
                .setEntityType(entityType)
                .setEntityUserId(String.valueOf(entityId));
        eventProducer.fireEvent(event);

        return CommunityUtil.getJsonString(0, "已关注！", null);
    }

    @PostMapping("/unfollow")
    @ResponseBody
    public String unfollow(int entityType, int entityId){
        User user = hostHolder.getUser();
        int userId = user.getId();
        try{
            followService.unfollow(entityType, entityId,userId);
        }catch (Exception e){
            logger.error("followService的unfollow方法报异常" + e.getMessage());
            return CommunityUtil.getJsonString(0, "取消关注失败！", null);
        }
        return CommunityUtil.getJsonString(0, "已取消关注！", null);
    }

}